var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
if(!config){
	config = parent.parent.parent.CONFIG;
	system = parent.parent.parent.SYSTEM;
}
var isRefresh = false;
var _limitMenu = system.MENULIMIT.BASE23;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'base/product/barcodelist';
var pdata = {};
var pd_code = $("#pd_code").val();
var pd_no = $("#pd_no").val();
var ST_SubCodeRule = $("#ST_SubCodeRule").val();//获取生成方式
var ST_SubCodeIsRule = $("#ST_SubCodeIsRule").val();
var subCodeRules = ST_SubCodeRule.split("+");//分割
var handle = {
	save:function(rowId){
		if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
			return;
		};
		var row=$('#grid').jqGrid('getRowData',rowId);
		$.ajax({
			type:"POST",
			url:config.BASEPATH +"base/product/saveOneBarcode",
			data:"bc_barcode="+row.bc_barcode+"&bc_id="+rowId,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : data.message});
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		}); 
	},
	del: function(rowId){//删除
		if(rowId != null && rowId != ''){
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH +"base/product/deleteBarcode",
					data:{"bc_id":rowId},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
						}else{
							Public.tips({type: 1, content : '删除失败!'});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
    callback: function(data, oper, dialogWin){
		var gridData = $("#grid").data('gridData');
		if(!gridData){
			gridData = {};
			$("#grid").data('gridData', gridData);
		}
		gridData[data.id] = data;
		if(oper == "edit") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		} 
		if(oper == "add"){
			$("#grid").jqGrid('addRowData', data.id, data, 'first');
		}
	},
	operFmatter:function(val, opt, row) {
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-shenpi" title="保存">&#xe616;</i> <i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	},
	getBarcode:function(pd_no,color,size,bra,pd_code){
		var barcode = "";
		if("0" == ST_SubCodeIsRule){
			barcode = pd_code+color+size+bra;
		}else{
			for(var i=0;i<subCodeRules.length;i++){
				if("货号"==subCodeRules[i]){
					barcode += pd_no;
					continue;
				}
				if("编码"==subCodeRules[i]){
					barcode += pd_code;
					continue;
				}
				if("颜色"==subCodeRules[i]){
					barcode += color;
					continue;
				}
				if("尺码"==subCodeRules[i]){
					barcode += size;
					continue;
				}
				if("杯型"==subCodeRules[i]){
					barcode += bra;
					continue;
				}
			}
		}
		return barcode;
	},
	changeBarcode:function(){
		var cr_code =$("#cr_code").val();
		var sz_code = $("#sz_code").val();
		var br_code = $("#br_code").val();
		$("#label_barcode").html(handle.getBarcode(pd_no,cr_code,sz_code,br_code,pd_code));
		$("#bc_sys_barcode").val(handle.getBarcode(pd_no,cr_code,sz_code,br_code,pd_code));
		$("#bc_subcode").val(pd_code + cr_code + sz_code + br_code);
		$("#bc_barcode").val("");
	},
	copyBarcode:function(){
		$("#bc_barcode").val(document.getElementById("label_barcode").innerHTML);
	},
	oneSaveBarcode:function(){
		var bc_barcode = $("#bc_barcode").val();
		if(bc_barcode == ""){
			Public.tips({type: 2, content : "请输入条形码！"});
			$("#bc_barcode").focus();
			return;
		}
		var cr_code =$("#cr_code").val();
		var sz_code = $("#sz_code").val();
		var br_code = $("#br_code").val();
		var bc_subcode = $("#bc_subcode").val();//子码
		var bc_sys_barcode =  $("#bc_sys_barcode").val();//系统条码
		$("#saveBar").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:config.BASEPATH +"base/product/saveOneBarcode",
			data:"bc_barcode="+bc_barcode+"&pd_no="+pd_no+"&pd_code="+pd_code+"&cr_code="+cr_code+"&sz_code="+sz_code+"&br_code="+br_code+"&bc_subcode="+bc_subcode+"&bc_sys_barcode="+bc_sys_barcode,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : data.message});
					THISPAGE.reloadData();
				}else{
					Public.tips({type: 1, content : data.message});
				}
				document.getElementById("bc_barcode").value = "";
				document.getElementById("bc_barcode").focus();
				$("#saveBar").attr("disabled",false);
			}
		}); 
	},
	printSet:function(){
    	$.dialog({
    		//id设置用来区别唯一性 防止div重复
    	   	id:'printPlan',
    	   	//设置标题
    	   	title:'条码打印设置',
    	   	//设置最大化最小化按钮(false：隐藏 true:关闭)
    	   	max: false,
    	   	min: false,
    	   	lock:true,
    	   	//设置长宽
    	   	width:440,
    	   	height:380,
    	   	//设置是否拖拽(false:禁止，true可以移动)
    	   	drag: true,
    	   	resize:false,
   		   	//设置页面加载处理
  		   	fixed:false,
    	   	content:"url:"+config.BASEPATH+"base/product/to_barcode_plan",
    	   	close: function(){
    	   		
  		   	}
        });
	},
	print:function(printState){//打印状态0直接打印 1打印预览
		var arrayObj = new Array();
		arrayObj=$('#grid').jqGrid('getGridParam','selarrrow');
		var i=0,addMark=0;
		if(arrayObj == "" ){
			Public.tips({type: 2, content : '没有可打印的记录！'});
            return;
        }
        var bc_barcodes = new Array();
        var bc_colornames = new Array();
        var bc_pd_nos= new Array();
        var bc_pd_names = new Array();
        var bc_branames = new Array();
       	var bc_sizenames = new Array();
       	var pd_bd_names = new Array();
       	var pd_sell_prices = new Array();
       	var pd_vip_prices = new Array();
       	var pd_sign_prices = new Array();
       	var pd_grades = new Array();
       	var pd_safes = new Array();
       	var pd_fills = new Array();
       	var pd_executes=new Array();
       	var pd_tp_names =new Array(); 
       	var pd_fabrics =new Array(); 
       	var pd_in_fabrics =new Array(); 
       	var pd_places =new Array(); 
    	var pd_wash_explains =new Array(); 
        if(arrayObj =="")
		{
			return;
		}
		else
		{
			var re= new RegExp("^[0-9]*[1-9][0-9]*$");//验证
			var tag = false;
			var k = 0;
			for (i=0; i<arrayObj.length; i++){
				if($("#grid").jqGrid('getCell', arrayObj[i],'bc_barcode')==""){
					Public.tips({type: 2, content : '请输入条形码！'});
					return;
				}
				var num = $("#grid").jqGrid('getCell', arrayObj[i],'sc_printnumber');
				if(num == ""){
					num = 1+"";
				}
				if(num.match(re)==null){
					Public.tips({type: 2, content : '打印数量只能输入正整数！'});
					return;
				}
				for(var n=0;n<num;n++){
					bc_barcodes[k] =$("#grid").jqGrid('getCell', arrayObj[i],'bc_barcode');
					bc_colornames[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_colorname');
					bc_pd_nos[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_pd_no');
					bc_branames[k] =  $("#grid").jqGrid('getCell', arrayObj[i],'bc_braname');
					bc_sizenames[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_sizename');
					pd_bd_names[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_bd_name');
					pd_sell_prices[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_sell_price');
					pd_vip_prices[k]= $("#grid").jqGrid('getCell', arrayObj[i],'pd_vip_price');
					pd_sign_prices[k]= $("#grid").jqGrid('getCell', arrayObj[i],'pd_sign_price');
					bc_pd_names[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_pd_name');
					pd_fills[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_fill');
					pd_safes[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_safe');
					pd_grades[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_grade');
					pd_executes[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_execute');
					pd_tp_names[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_tp_name');
					pd_fabrics[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_fabric');
					pd_in_fabrics[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_in_fabric');
					pd_places[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_place');
					pd_wash_explains[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_wash_explain');
					k++;
					addMark++;
				}
			}
		}
		if(addMark==0)
		{
			Public.tips({type: 2, content : '请选择要打印的条形码！'});
			return;	
		}
		
		xdPrint.barCode(printState,bc_barcodes,bc_colornames,bc_pd_nos,bc_branames,bc_sizenames,pd_bd_names,pd_sell_prices,pd_sign_prices,pd_vip_prices,pd_grades,pd_safes,pd_fills,bc_pd_names,pd_executes,pd_tp_names,pd_fabrics,pd_in_fabrics,pd_places,pd_wash_explains);
	}
};

function buildUrlParams(){
	var params="pd_code="+$("#pd_code").val();
	return params;
};
var ComboUtil = {
	colorCombo:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH +"base/product/colorByProduct?pd_code="+pd_code,
			cache:false,
			dataType:"json",
			success:function(data){
				var colorInfo = {};
				colorCombo = $('#span_color').combo({
					data:data.data.items,
					value: 'cr_code',
					text: 'cr_name',
					width : 82,
					height : 80,
					listId:'',
					defaultSelected: 0,
					editable: true,
					ajaxOptions:{
						formatData: function(data){
							colorInfo = data.data.items;
							return data.data.items;
						}
					},
					callback:{
						onChange: function(data){
							$("#cr_code").val(data.cr_code);
							handle.changeBarcode();
						}
					}
				}).getCombo(); 
			}
		 });
	},
	sizeCombo:function(){
		var pd_szg_code = $("#pd_szg_code").val();
		$.ajax({
			type:"POST",
			url:config.BASEPATH +"base/product/sizeByProduct?szg_code="+pd_szg_code,
			cache:false,
			dataType:"json",
			success:function(data){
				var sizeInfo = {};
				sizeCombo = $('#span_size').combo({
					data:data.data.items,
					value: 'sz_code',
					text: 'sz_name',
					width : 82,
					height : 80,
					listId:'',
					defaultSelected: 0,
					editable: true,
					ajaxOptions:{
						formatData: function(data){
							sizeInfo = data.data.items;
							return data.data.items;
						}
					},
					callback:{
						onChange: function(data){
							$("#sz_code").val(data.sz_code);
							handle.changeBarcode();
						}
					}
				}).getCombo(); 
			}
		 });
	},
	braCombo:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH +"base/product/braByProduct?pd_code="+pd_code,
			cache:false,
			dataType:"json",
			success:function(data){
				var braInfo = {};
				braCombo = $('#span_bra').combo({
					data:data.data.items,
					value: 'br_code',
					text: 'br_name',
					width : 82,
					height : 80,
					listId:'',
					defaultSelected: 0,
					editable: true,
					ajaxOptions:{
						formatData: function(data){
							braInfo = data.data.items;
							return data.data.items;
						}
					},
					callback:{
						onChange: function(data){
							$("#br_code").val(data.br_code);
							handle.changeBarcode();
						}
					}
				}).getCombo(); 
			}
		 });
	}
}
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		ComboUtil.colorCombo();
		ComboUtil.sizeCombo();
		var pd_bra = $("#pd_bra").val();//如果不是文胸 初始化不查询杯型信息
		if(pd_bra == "1"){
			ComboUtil.braCombo();
		}
		handle.changeBarcode();
	},
	initGrid:function(){
		var colModel = [
		    {name: 'operate', label:'操作',width: 60, fixed:true, formatter: handle.operFmatter, title: false,sortable:false},
	    	{name: 'bc_colorname',label:'颜色',index: 'bc_colorname',width: 80,title: false,fixed:true},
	    	{name: 'bc_sizename',label:'尺码',index: 'bc_sizename',width: 80,title: false},
	    	{name: 'bc_braname',label:'杯型',index: 'bc_braname',width: 60,title: false},
	    	{name: 'bc_sys_barcode',label:'系统条形码',index: 'bc_sys_barcode', width: 150,title: false},
	    	{name: 'bc_barcode',label:'自建条形码',index: 'bc_barcode', width: 150,title: false,editable:true},
	    	{name: 'sc_printnumber',label:'打印数量', index: 'sc_printnumber', width: 80, editable:true, title: false},
	    	{label:'',name: 'bc_pd_no', index: 'bc_pd_no', title: false,fixed:true,hidden:true},
	    	{label:'',name: 'bc_pd_name', index: 'bc_pd_name', title: false,hidden:true},
	    	{label:'',name: 'pd_bd_name', index: 'pd_bd_name', title: false,hidden:true},
//	    	{label:'',name: 'ct_name', index: 'SC_Ct_Name', width:80, title: false,align:'center',hidden:true},
	    	{label:'',name: 'pd_sell_price', index: 'pd_sell_price',title: false,hidden:true},
	    	{label:'',name: 'pd_grade', index: 'pd_grade', title: false,hidden:true},
	    	{label:'',name: 'pd_safe', index: 'pd_safe', title: false,hidden:true},
	    	{label:'',name: 'pd_fill', index: 'pd_fill', title: false,hidden:true},
	    	{label:'',name: 'pd_sign_price', index: 'pd_sign_price',title: false,hidden:true},
	    	{label:'',name: 'pd_vip_price', index: 'pd_vip_price',title: false,hidden:true},
	    	{label:'',name: 'pd_execute', index: 'pd_execute',title: false,hidden:true},
	    	{name: 'pd_tp_name',label:'类别',hidden:true},
	    	{name: 'pd_fabric',label:'面料',hidden:true},
	    	{name: 'pd_in_fabric',label:'里料',hidden:true},
	    	{name: 'pd_place',label:'产地',hidden:true},
	    	{name: 'pd_wash_explain',label:'洗涤说明',hidden:true}
	    ];
		var params=buildUrlParams(); 
		$('#grid').jqGrid({
			url:queryurl+"?"+params,
			datatype: 'json',
			width:750,
			height: 290,
			gridview: true,
			onselectrow: false,
			cellEdit: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:true,//多选
			viewrecords: true,
			cellsubmit: 'clientArray',//可编辑列在编辑完成后会触发保存事件，clientArray表示只保存到表格不提交到服务器
			rowNum:30,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:true,//表格是否自动填充
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'bc_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){
			}
	    });
	},
	reloadData:function(data){
		var param="?";
		param += buildUrlParams(); 
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//删除
		$('#grid').on('click', '.operating .ui-icon-trash', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.del(id);
		});
		 //修改
        $('#grid').on('click', '.operating .ui-icon-shenpi', function (e) {
            var id = $(this).parent().data('id');
        	handle.save(id);
        });
        //打印设置
		$('#btn-printSite').on('click', function(e){
			e.preventDefault();
			handle.printSet();
		});
		//打印
		$('#btn-print').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.PRINT)) {
				return ;
			}
			handle.print(0);
		});
		$('#btn-print-preview').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.PRINT)) {
				return ;
			}
			handle.print(1);
		});
	}
}
THISPAGE.init();